import { ConfigEnv, loadEnv, UserConfig } from 'vite';
import { resolve } from 'path';
import uni from '@dcloudio/vite-plugin-uni';
import TransformPages from 'uni-read-pages-vite';
import eslintPlugin from 'vite-plugin-eslint';

export default ({ mode }: ConfigEnv): UserConfig => {
    const root = process.cwd();
    const env = loadEnv(mode, root);
    console.log('root==', root, 'env==', env);

    return {
        base: './',
        resolve: {
            alias: {
                '@': resolve('./src'),
            },
            extensions: ['.js', '.json', '.ts', '.vue'],
        },
        define: {
            'process.env': {},
            ROUTES: new TransformPages().routes,
        },
        server: {
            host: true,
            open: true,
            port: env.VITE_PORT as any,
            proxy: {
                '/api': {
                    target: env.VITE_BASE_URL,
                    changeOrigin: true,
                    rewrite: (path) => path.replace(/^\/api/, ''),
                },
                '/upload': {
                    target: env.VITE_BASE_URL,
                    changeOrigin: true,
                    rewrite: (path) => path.replace(/^\/upload/, ''),
                },
            },
        },
        build: {
            outDir: 'dist',
            chunkSizeWarningLimit: 3000,
            minify: 'terser',
            terserOptions: {
                compress: {
                    drop_console: true,
                },
            },
            rollupOptions: {
                output: {
                    chunkFileNames: 'assets/js/[name]-[hash].js',
                    entryFileNames: 'assets/js/[name]-[hash].js',
                    assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
                },
            },
            // 关闭文件计算
            reportCompressedSize: false,
            sourcemap: false, // 这个生产环境一定要关闭，不然打包的产物会很大
        },
        plugins: [
            uni(),
            eslintPlugin({
                include: ['src/**/*.ts', 'src/**/*.vue', 'src/*.ts', 'src/*.vue'],
            }),
        ],
        css: {
            preprocessorOptions: {
                scss: {
                    additionalData: '@import "uniapp-nutui/styles/variables.scss";',
                },
            },
        },
    };
};
